
const superagent = require('superagent');
const getAccessToken = require('tools/dd/getAccessToken');
const { createToken } = require('tools/token');
const log = require('tools/log');

module.exports = async ctx => {
    try {
        const code = getCode(ctx);
        const company = ctx.headers["company-id"];
        const access_token = await getAccessToken(company);
        const userid = await getUserId(access_token, code);
        const userInfo = await getUserInfo(access_token, userid);
        const token = createToken(userInfo, new Date().getTime());
        ctx.status = 200;
        ctx.body = { userInfo, token };
    } catch (error) {
        ctx.status = error.code || 500;
        ctx.body = error;
    }
}

/** 获取 code */
function getCode(ctx) {
    try {
        if (ctx.request.body.code) {
            return ctx.request.body.code;
        } else {
            throw { code: 501, data: "CODE 出错误" }
        }
    } catch (error) {
        throw error
    }
}

/** 获取userid */
function getUserId(access_token, code) {
    return new Promise((resolve, reject) => {
        superagent.post('https://oapi.dingtalk.com/topapi/v2/user/getuserinfo')
            .query({ access_token })
            .send({ code })
            .end((error, res) => {
                try {
                    if (error) throw error;
                    if (res.body.errcode !== 0) throw res.body;
                    resolve(res.body.result.userid);
                } catch (error) {
                    log('===> err https://oapi.dingtalk.com/topapi/v2/user/getuserinfo');
                    log(error)
                    reject({ code: 503, data: error })
                }
            })
    })
}

/** 获取用户数据 */
function getUserInfo(access_token, userid) {
    return new Promise((resolve, reject) => {
        superagent.post('https://oapi.dingtalk.com/topapi/v2/user/get')
            .query({ access_token })
            .send({ userid })
            .end((error, res) => {
                try {
                    if (error) throw error;
                    if (res.body.errcode !== 0) throw res.body
                    resolve(res.body.result);
                } catch (error) {
                    reject({ code: 504, data: error })
                }
            })
    })
}